import { getSignature, decrypt } from '@wecom/crypto';
import * as xml2js from 'xml2js';
import config from 'config';

const { token, encodingAESKey }: qyProps = config.get('qy');

export interface qyProps {
  suiteId: string;
  suiteSecret: string;
  baseUrl: string;
  qyBaseUrl: string;
  token: string;
  encodingAESKey: string;
}

interface XmlProps<T> {
  xml: T;
}

// 获取临时授权码
const getMsg = async <T>(timestamp: number, nonce: string, encrypt: string, msgSignature: string) => {
  const msg = await decodeMsg(timestamp, nonce, encrypt, msgSignature);
  if (msg && msg.message) {
    const msgJson: XmlProps<T> = await xml2js.parseStringPromise(msg.message);
    return msgJson.xml;
  } else {
    return;
  }
};

// 判断签名并解密数据
const decodeMsg = async <T>(timestamp: number, nonce: string, encrypt: string, msgSignature: string) => {
  const mySignature = getSignature(token, timestamp, nonce, encrypt);
  if (mySignature === msgSignature) {
    const msg = decrypt(encodingAESKey, encrypt);
    return msg;
  }
  return;
};

export { getMsg, decodeMsg };
